import React, { useEffect, useState, useContext } from 'react';
import { Message, Card, Modal, Input, Button, Row, Col, Table, InputNumber, Popconfirm, Form, Typography, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import classnames from 'classnames';

import styles from './style.module.scss';

import WebsiteName from 'components/WebsiteName';
import Navigate from 'components/Navigate';
import Beian from 'components/Beian';

import service from 'service'
import Home, { HomeContext } from './context';
import { isFunction } from 'utils/util';

const { confirm } = Modal;

const accountsRules = {
    site: [{ required: false, message: "" }],
    website: [{ required: true, message: "网址不可为空" }, { pattern: /^((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)$/, message: "请输入正确的网址" }],
    introduction: [{ required: false, message: "" }],
    account: [{ required: true, message: "账号不可为空" }],
    password: [{ required: false, message: "" }],
    associates: [{ required: false, message: "" }],
    nickname: [{ required: false, message: "" }],
    status: [{ required: false, message: "" }, { pattern: /[012]/, message: "状态参数错误" }],
    remark: [{ required: false, message: "" }],
    tags: [{ required: false, message: "" }], // 数组字符串
}

const originData = [];

for (let i = 0; i < 100; i++) {
    originData.push({
        key: i.toString(),
        website: `菜鸟`,
        account: `13777072`,
        status: 32,
    });
}
// 参考这段
// https://www.runoob.com/tags/tag-input.html
const EditableRow = (props) => {
    console.log(props)
    return <tr data-row-key={props['data-row-key']} class="ant-table-row ant-table-row-level-0 editable-row">
        <Form onFinish={(values) => console.log(values)}>
            <Form.List name="users">
                {(fields, { add, remove }) => (
                    <>
                        {fields.map(({ key, name, fieldKey, ...restField }) => (
                            <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                <Form.Item
                                    {...restField}
                                    name={[name, 'first']}
                                    fieldKey={[fieldKey, 'first']}
                                    rules={[{ required: true, message: 'Missing first name' }]}
                                >
                                    <Input placeholder="First Name" />
                                </Form.Item>
                                <Form.Item
                                    {...restField}
                                    name={[name, 'last']}
                                    fieldKey={[fieldKey, 'last']}
                                    rules={[{ required: true, message: 'Missing last name' }]}
                                >
                                    <Input placeholder="Last Name" />
                                </Form.Item>
                                <MinusCircleOutlined onClick={() => remove(name)} />
                                <Form.Item>
                                    <Button htmlType="submit" type="primary" >确定</Button>
                                </Form.Item>
                            </Space>
                        ))}
                        <Form.Item>
                            <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>Add field </Button>
                        </Form.Item>
                    </>
                )}
            </Form.List>
        </Form>
    </tr >
}
const EditableCell = (props) => {
    let {
        editing, //状态:编辑|未编辑
        title, // 标题名
        dataIndex, // 字段名
        inputType, // 类型
        record, // 此行数据
        index, // ?
        children, // ?
        editRender,
        ...restProps // 原始信息
    } = props
    console.log(props, index, restProps, editing)
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
    return (
        <td {...restProps}>
            {/* {editing ? (editRender ? editRender({ title, dataIndex, record }) : children) : children} */}
            {editing ? (
                <Form.Item
                    website={dataIndex}
                    style={{
                        margin: 0,
                    }}
                    rules={[
                        {
                            required: true,
                            message: `Please Input ${title}!`,
                        },
                    ]}
                >
                    {inputNode}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};

const addHandleFn = (list, cb) => {
    const add = (key) => {
        console.log(list)
        let keys = [...list, key];
        if (cb) {
            return cb(keys)
        }
        return keys
    }
    const remove = (key) => {
        let fn = (item) => {
            return item.key !== key
        }
        if (isFunction(key)) {
            fn = key;
        }
        let keys = list.filter(fn);
        if (cb) {
            return cb(keys)
        }
        return keys
    }
    return { add, remove }
}
export default () => {
    // 取出存放在localStorage中的批量添加列表
    const batchAddList = localStorage.getItem('batchAddList');
    const storageList = batchAddList ? batchAddList : [];
    const [list, setList] = useState(storageList);
    const [form] = Form.useForm();
    // data的操作方法
    const [data, setData] = useState(storageList);
    let datasHandle = addHandleFn(data, setData);
    // editingKey的操作方法
    const [editingKey, setEditingKey] = useState([]);
    let editingKeysHandle = addHandleFn(editingKey, setEditingKey);

    const isEditing = (record) => editingKey.includes(record.key);

    const edit = (record) => {
        form.setFieldsValue({
            website: '',
            status: '',
            account: '',
            ...record,
        });
        setEditingKey(record.key);
    };

    const cancel = () => {
        setEditingKey('');
    };

    const save = async (key) => {
        try {
            const row = await form.validateFields();
            console.log(row)
            const newData = [...data];
            const index = newData.findIndex((item) => key === item.key);

            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row });
                setData(newData);
                setEditingKey('');
            } else {
                newData.push(row);
                setData(newData);
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };

    const columns = [
        {
            title: 'website',
            dataIndex: 'website',
            width: '25%',
            editable: true,
            inputType: 'text',
            editRender: (data) => {
                console.log(data)
                let { record, title, dataIndex } = data || {};
                return (
                    <Form.Item
                        website={dataIndex}
                        style={{
                            margin: 0,
                        }}
                        rules={[
                            {
                                required: true,
                                message: `Please Input ${title}!`,
                            },
                        ]}
                    >
                        <Input placeholder={'请输入' + title} defaultValue={record[dataIndex]} />
                    </Form.Item>
                )
            }
        },
        {
            title: 'account',
            dataIndex: 'account',
            width: '40%',
            editable: true,
            inputType: 'text',
            editRender: (data) => {
                console.log(data)
                let { record, title, dataIndex } = data || {};
                return (
                    <Form.Item
                        website={dataIndex}
                        style={{
                            margin: 0,
                        }}
                        rules={[
                            {
                                required: true,
                                message: `Please Input ${title}!`,
                            },
                        ]}
                    >
                        <Input placeholder={'请输入' + title} />
                    </Form.Item>
                )
            }
        },
        {
            title: 'status',
            dataIndex: 'status',
            width: '15%',
            editable: true,
            inputType: 'number',
            editRender: (data) => {
                console.log(data)
                let { record, title, dataIndex } = data || {};
                return (
                    <Form.Item
                        website={dataIndex}
                        style={{
                            margin: 0,
                        }}
                        rules={[
                            {
                                required: true,
                                message: `Please Input ${title}!`,
                            },
                        ]}
                    >
                        <Input placeholder={'请输入' + title} />
                    </Form.Item>
                )
            }
        },
        {
            title: 'operation',
            dataIndex: 'operation',
            render: (_, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <a
                            onClick={() => save(record.key)}
                            style={{
                                marginRight: 8,
                            }}
                        >
                            Save
            </a>
                        <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
                            <a>Cancel</a>
                        </Popconfirm>
                        <a onClick={() => { removeOne(record.key) }} style={{ marginRight: 8 }} > 删除 </a>
                    </span>
                ) : (
                    <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                        Edit
                    </Typography.Link>
                );
            },
        },
    ];
    const mergedColumns = columns.map((col, index) => {
        if (!col.editable) {
            return col;
        }
        let { inputType, editRender } = col;
        return {
            ...col,
            onCell: (record) => ({
                record,
                inputType,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
                index,
                editRender
            }),
        };
    });
    console.log(data)

    // 新增一行
    const createOne = () => {
        console.log('新增')
        let key = new Date().getTime().toString();
        datasHandle.add({
            key,
            website: `菜鸟`,
            account: `13777072`,
            status: 32,
            // key,
            // website: ``,
            // account: ``,
            // status: 0,
        })
        editingKeysHandle.add(key);
    }
    // 删除某一行
    const removeOne = (key) => {
        console.log('移出', key)
        datasHandle.remove((item) => {
            return item.key !== key
        })
        editingKeysHandle.remove(key);
    }

    // useEffect(() => {

    // })
    return (
        <div className={styles.container}>
            <div className={classnames(styles.header, styles.bg)}>
                <div className={styles.headerContent}>
                    <div className={styles.title}>
                        <WebsiteName />
                        <Navigate />
                    </div>
                    <div className={styles.operation}>
                    </div>
                </div>
            </div>
            <div className={classnames(styles.content, styles.bg)}>
                <Form form={form} component={false} onFinish={(values) => console.log(values)}>
                    <Table
                        components={{
                            body: {
                                // row: EditableRow,
                                cell: EditableCell,
                            },
                        }}
                        bordered
                        dataSource={data}
                        columns={mergedColumns}
                        pagination={{
                            onChange: cancel,
                        }}
                    />
                    <Button onClick={createOne}>新增一行</Button>
                    <Button onClick={removeOne}>删除一行</Button>
                    <Form.Item>
                        <Button htmlType="submit" type="primary" >确定</Button>
                    </Form.Item>
                </Form>
            </div>
            <div className={classnames(styles.footer, styles.bg)}>
                <Beian />
            </div>
        </div >
    )
}